/**
 * @author Chris Wilcox
 * @author Preston Parrett
 * 
 * @date 2008/03/17
 * 
 * The Evolution program was written for UCSB's CS165b class.
 * 
 */

package evolution;

import java.util.Timer;
import java.util.TimerTask;


public class God extends Thread {
	
	public World world;
	
	private int tickLength;
	private int yearLength;
	//private boolean run = true;
	private Timer timer;
	private WorldRunner currentRunner;
	
	public God() {
		super("The Universe");
		tickLength(100);
		timer = new Timer(true);
		yearLength(100);
	}
	
	private class WorldRunner extends TimerTask {
		public void run() {
			world.tick();
			
			// If another year worth of ticks then create new population
			int numTicks = (int)Stats.getStatValue("Number ticks");			

			if (numTicks % yearLength == 0){		
				world.newYear();				
			}
			
		}
	}
	
	
	public World createWorld() {
		destroyWorld();
		world = new World(50,50);
		world.populateWorld(500,10);
		//world.populateWorld(60,new Consumer[](this));
		return world;
	}
	
	public World getWorld() {
		return world;
	}
	
	public void destroyWorld() {
		pause();
		world = null;
	}
	
	public void tickLength(int milliseconds) {
		if (milliseconds <= 0) return;
		tickLength = milliseconds;
		Stats.reportWithReset("Ticks per sec", 1/((float)milliseconds/1000));
		
		pause();
		start();
	}
	
	public void yearLength(int ticks) {
		if (ticks <= 0) return;
		yearLength = ticks;
		Stats.reportWithReset("Ticks per year", (float)ticks);
		
		pause();
		start();
	}
	
	public void pause() {
		if (currentRunner != null) {
			currentRunner.cancel();
			currentRunner = null;
		}
	}
	
	public void start() {
		if (world == null) return;
		currentRunner = new WorldRunner();
		timer.schedule(currentRunner,0,tickLength);
	}
}
